import React, { useEffect, useState } from 'react';
import Header from './components/Layout/Header';
import Sidebar from './components/Layout/Sidebar';
import DataSourceManager from './components/DataSourceManager/DataSourceManager';
import './assets/styles/index.css';
import API from './api/client';

function App() {
  const [showAddDataSourceModal, setShowAddDataSourceModal] = useState(false);
  const [dataSourceTypes, setDataSourceTypes] = useState([]);
  const [dataSources, setDataSources] = useState({ items: [] });
  const [erModels, setErModels] = useState({ items: [] });
  const [loadingTypes, setLoadingTypes] = useState(false);
  const [errorLoadingTypes, setErrorLoadingTypes] = useState(null);
  
  // 获取数据源类型
  const fetchDataSourceTypes = async () => {
    try {
      const response = await API.getDataSourceTypes();
      
      return response
    } catch (error) {
      console.error('数据源类型加载失败:', error);
      return []; // 始终返回数组
    }
  };

  // 获取所有数据源
  const fetchDataSources = async () => {
    try {
      const response = await API.getDataSources();
      
      // 处理不同数据结构
      let items = [];
      if (Array.isArray(response)) {
        items = response;
      } else if (response && Array.isArray(response.items)) {
        items = response.items;
      } else if (response && response.data) {
        items = Array.isArray(response.data) ? response.data : [response.data];
      }
      
      setDataSources({ items, meta: response.meta || {} });
    } catch (error) {
      console.error('加载数据源失败:', error);
      setDataSources({ items: [], meta: {} });
    }
  };

  useEffect(() => {
    const loadData = async () => {
      const types = await fetchDataSourceTypes();
      // console.log("data source type: "+types)
      setDataSourceTypes(types); // 设置数组类型状态
    };
    loadData();
  }, []);

  // 初始化数据
  useEffect(() => {
    fetchDataSourceTypes();
    fetchDataSources();
  }, []);

  return (
    <div className="app-layout">
      <Header />
      <Sidebar 
        onAddDataSourceClick={() => setShowAddDataSourceModal(true)}
        dataSourceTypes={dataSourceTypes}
        dataSources={dataSources}
        erModels={erModels}
        refreshDataSources={fetchDataSources}
      />
      <main className="main-content">
        <DataSourceManager 
          showAddDataSourceModal={showAddDataSourceModal}
          closeDataSourceModal={() => setShowAddDataSourceModal(false)}
          refreshDataSources={fetchDataSources}
          dataSourceTypes={dataSourceTypes}
          erModels={erModels}
        />
      </main>

      <div id="modal-root"></div>
    </div>
  );
}

export default App;